import axios from 'axios'
const qs = require('qs')

// axios基本配置
axios.defaults.timeout = 5000


// http request 拦截器
axios.interceptors.request.use(config => {
    console.log("config",config)
    if(config.method==='post'){
        config.data = qs.stringify(config.data)
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(response => {
        return response.data
  
  },
  error => {
    return Promise.reject(error)
})


const http = {
    /**
     * post 请求方法
     * @param url
     * @param data
     * @returns {Promise}
     */
    post (url, data) {
        return new Promise((resolve, reject) => {
            axios.post(url, data).then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
        })
    },
    /**
     * get 请求方法
     * @param url
     * @param data
     * @returns {Promise}
     */
    get (url, data) {
        return new Promise((resolve, reject) => {
            axios.get(url, {params:data}).then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
        })
    },
    /**
     * put 请求方法
     * @param url
     * @param id
     * @param data
     * @returns {Promise}
     */
    put (url, id, data) {
        return new Promise((resolve, reject) => {
            axios.put(url + id, data).then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
        })
    },
    /**
     * delete 请求方法
     * @param url
     * @param id
     * @returns {Promise}
     */
   delete (url, data) {
        return new Promise((resolve, reject) => {
            axios.delete(url,{params: data}).then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
        })
    }
}


export default http